package com.th.aip.service.impl;

import com.baidu.aip.ocr.AipOcr;
import com.th.aip.config.AipConfig;
import com.th.aip.config.AipConfigProperties;
import com.th.aip.service.AipService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;



/**
 * @author ErrorRua
 * @date 2023/06/24
 * @description:
 */
@Service
@EnableConfigurationProperties(AipConfigProperties.class)
@Import(AipConfig.class)
public class AipServiceImpl implements AipService {

    @Autowired
    private AipOcr aipOcr;

    @Override
    public HashMap<String, String> identifyIdcard(String frontImage, String backImage, String IdNumber, String name) {
        JSONObject frontJson = aipOcr.idcard(getFile(frontImage), "front", null);
        JSONObject backJson = aipOcr.idcard(getFile(backImage), "back", null);

        HashMap<String, String> map = new HashMap<>();

         if(!checkStatus(frontJson, backJson, map)) {
             return map;
         }

        if (!checkKeyword(frontJson, IdNumber, name, map)) {
            return map;
        }

        map.put("result", "0");

        return map;
    }

    private boolean checkStatus(JSONObject frontJson, JSONObject backJson, Map<String, String> map) {
        String frontImageStatus = (String) frontJson.get("image_status");
        String frontStatus = getStatus(frontImageStatus);

        String backImageStatus = (String) backJson.get("image_status");
        String backStatus = getStatus(backImageStatus);

        StringBuilder message = new StringBuilder();
        if (!frontStatus.equals("识别正常")) {
            message.append("身份证(人像面):").append(frontStatus);
        }
        if (!backStatus.equals("识别正常")) {
            message.append(",身份证(国徽面):").append(backStatus);
            map.put("message", message.toString());
            map.put("result", "1");
            return false;
        }
        return true;
    }

    private boolean checkKeyword(JSONObject frontJson, String IdNumber, String name, Map<String, String> map) {
        JSONObject frontWordsResult = (JSONObject) frontJson.get("words_result");
        JSONObject frontIdNumber = (JSONObject) frontWordsResult.get("公民身份号码");
        JSONObject frontName = (JSONObject) frontWordsResult.get("姓名");
        String frontIdentifyIdNumber = (String) frontIdNumber.get("words");
        String frontIdentifyName = (String) frontName.get("words");

        if (!frontIdentifyIdNumber.equals(IdNumber)) {
            map.put("message", "身份证号码与身份证不一致");
            map.put("result", "2");
            return false;
        }
        if (!frontIdentifyName.equals(name)) {
            map.put("message", "姓名与身份证不一致");
            map.put("result", "2");
            return false;
        }
        return true;
    }

    private String getStatus(String imageStatus) {
        switch (imageStatus) {
            case "normal":
                return "识别正常";
            case "reversed_side":
                return "未摆正身份证";
            case "non_idcard":
                return "上传的图片中不包含身份证";
            case "blurred":
                return "身份证模糊";
            case "over_exposure":
                return "身份证关键字段反光或过曝";
            default:
                return "未知错误";
        }
    }

    /**
     * 得到文件流
     * @param url  网络图片URL地址
     * @return
     */
    private byte[] getFile(String url){
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    private byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}
